//
//  Const.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/16.
//

import UIKit

let customTabBarHeight = 58.0
let SCREEN_WIDTH: CGFloat = UIScreen.main.bounds.width
let SCREEN_HEIGHT: CGFloat = UIScreen.main.bounds.height

// 状态栏高度
public var statusBarHeight: CGFloat {
    guard let window = UIApplication.shared.currentKeyWindow else { return 20.0 }
    return window.windowScene?.statusBarManager?.statusBarFrame.height ?? 20.0
}

extension UIWindow {
    /// 全局安全区域（兼容 iOS 11+）
    static var safeAreaInsets: UIEdgeInsets {
        if #available(iOS 11.0, *) {
            return UIApplication.shared.windows.first?.safeAreaInsets ?? .zero
        } else {
            return .zero
        }
    }
}

/// 顶部安全区域（刘海屏等）
var topMargin: CGFloat {
    return UIWindow.safeAreaInsets.top
}

/// 底部安全区域（Home Indicator 等）
var bottomMargin: CGFloat {
    return UIWindow.safeAreaInsets.bottom
}

extension Dictionary where Key == String, Value == Any {
    /// 将字典转换为URL查询参数字符串
    func toURLQueryString() -> String {
        return self.compactMap { key, value in
            // 确保key和value都是字符串
            let encodedKey = key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
            let stringValue = String(describing: value)
            let encodedValue = stringValue.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
            
            return "\(encodedKey)=\(encodedValue)"
        }
        .sorted() // 可选：按字母顺序排序参数
        .joined(separator: "&")
    }
}

func generateRandomString() -> String {
    let length = Int.random(in: 6...10)
    let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    return String((0..<length).map { _ in letters.randomElement()! })
}

func stringFormatToDate(dateString: String) -> Date? {
    // 创建日期格式化器
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"
    return dateFormatter.date(from: dateString)
}

func dateToFormatString(date: Date) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"
    return dateFormatter.string(from: date)
}


func dictionaryToBase64(dict: [String: Any]) -> String? {
    do {
        // 1. 将字典转换为JSON数据
        let jsonData = try JSONSerialization.data(withJSONObject: dict, options: [])
        
        // 2. 将JSON数据转换为Base64字符串
        let base64String = jsonData.base64EncodedString()
        
        return base64String
    } catch {
        print("字典转Base64失败: \(error.localizedDescription)")
        return nil
    }
}

func convertDictionaryArrayToBase64(_ array: [[String: Any]]) -> String? {
    do {
        // 1. 将字典数组转换为JSON数据
        let jsonData = try JSONSerialization.data(withJSONObject: array, options: [])
        
        // 2. 将JSON数据转换为Base64字符串
        let base64String = jsonData.base64EncodedString()
        
        return base64String
    } catch {
        print("字典数组转Base64失败: \(error.localizedDescription)")
        return nil
    }
}

// 用于单个值（Int/String → String）
@propertyWrapper
struct IntOrString: Codable {
    var wrappedValue: String?
    
    init(wrappedValue: String?) {
        self.wrappedValue = wrappedValue
    }
    
    init(from decoder: Decoder) throws {
        // 关键点：使用能捕获 keyNotFound 的容器
        let container = try decoder.singleValueContainer()
        
        // 尝试解码 Int -> String
        if let intValue = try? container.decode(Int.self) {
            wrappedValue = String(intValue)
        }
        // 尝试解码 String
        else if let stringValue = try? container.decode(String.self) {
            wrappedValue = stringValue
        }
        // 如果都不是，保持 nil
        else {
            wrappedValue = nil
        }
    }
}

// MARK: - 关键扩展：使属性包装器支持自动处理缺失 key
extension KeyedDecodingContainer {
    // 新方法名避免递归
    func decodeAuto<T: Decodable>(_ type: T.Type, forKey key: Key) throws -> T {
        if type == IntOrString.self {
            return (try decodeIfPresent(IntOrString.self, forKey: key) ?? IntOrString(wrappedValue: nil)) as! T
        }
        // 对于其他类型，使用基础解码方法
        return try decode(T.self, forKey: key)
    }
}

// 用于数组（[Int]/[String] → [String]）
@propertyWrapper
struct IntArrayOrStringArray: Codable {
    var wrappedValue: [String]?
    
    init(wrappedValue: [String]?) {
        self.wrappedValue = wrappedValue
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let intArray = try? container.decode([Int].self) {
            wrappedValue = intArray.map { String($0) }
        } else {
            wrappedValue = try? container.decode([String].self)
        }
    }
}
